package com.chushouya.order.service.api.impl;

import com.chushouya.common.dto.suhuishou.ResponseDTO;
import com.chushouya.common.util.SuhuishouRequest;
import com.chushouya.order.service.common.SuhuishouSyncService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Jsons;
import com.chushouya.manager.config.BizConfigEnum;
import com.chushouya.manager.service.common.ConfigApiService;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.constants.OrderTypeEnum;
import com.chushouya.order.dao.entity.OrderAddressEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderProductEntity;
import com.chushouya.order.dao.repository.OrderAddressRepository;
import com.chushouya.order.dao.repository.OrderProductRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.api.suhuishou.SuhuishouOrderSubmitDTO;
import com.chushouya.order.service.api.SuhuishouOrderApiService;
import com.chushouya.order.service.common.OrderLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.chushouya.common.constant.SuhuishouConstants.SUHUISHOU_ORDER_CANCEL;
import static com.chushouya.common.constant.SuhuishouConstants.SUHUISHOU_ORDER_CREATE;

/**
 * 速回收订单API服务实现
 * 
 * @author system
 */
@Slf4j
@Service
public class SuhuishouOrderApiServiceImpl implements SuhuishouOrderApiService {

    @Resource
    private SuhuishouRequest suhuishouRequest;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderProductRepository orderProductRepository;

    @Resource
    private OrderAddressRepository orderAddressRepository;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    private ConfigApiService configApiService;

    @Resource
    private SuhuishouSyncService suhuishouSyncService;

    @Override
    public ResponseDTO<SuhuishouOrderSubmitDTO> createSuhuishouOrder(Long orderId) {
        try {
            log.info("开始创建速回收订单，订单ID: {}", orderId);

            // 获取订单地址信息
            OrderAddressEntity orderAddress = getOrderAddress(orderId);
   
            // 获取订单信息
            OrderEntity orderInfo = getOrderInfo(orderId);
                     // 验证用户地址
            validateOrderSyncConditions(orderInfo, orderAddress);
            // 获取订单产品信息
            OrderProductEntity orderProduct = getOrderProduct(orderId);

            // 构建请求参数
            Map<String, Object> params = buildCreateOrderParams(orderInfo, orderProduct, orderAddress);
            
            log.info("创建速回收订单请求参数: {}", Jsons.toJsonString(params));

            // 调用速回收API创建订单
            ResponseDTO<SuhuishouOrderSubmitDTO> response = suhuishouRequest.httpRequest(
                SUHUISHOU_ORDER_CREATE, 
                "POST", 
                params, SuhuishouOrderSubmitDTO.class
            );

            log.info("速回收订单创建响应: {}", Jsons.toJsonString(response));

            // 处理响应结果
            if (response != null && response.getCode() == 200) {
                // 订单创建成功，可以在这里添加后续处理逻辑
                // 比如更新本地订单状态、记录日志等
                handleCreateOrderSuccess(orderId, response);
                log.info("速回收订单创建成功，订单ID: {}", orderId);
            } else {
                log.error("速回收订单创建失败，订单ID: {}, 响应: {}", orderId, response);
            }

            return response;

        } catch (Exception e) {
            log.error("创建速回收订单异常，订单ID: {}", orderId);
            throw Ex.business("创建订单失败: {}" , e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Object> cancelSuhuishouOrder(String orderNo, String remark) {
        try {
            log.info("开始取消速回收订单，订单号: {}, 备注: {}", orderNo, remark);

            // 构建取消订单参数
            Map<String, Object> params = new HashMap<>();
            params.put("orderNo", orderNo);
            params.put("remark", remark != null ? remark : "");

            log.info("取消速回收订单请求参数: {}", Jsons.toJsonString(params));

            // 调用速回收API取消订单
            ResponseDTO<Object> response = suhuishouRequest.httpRequest(
                SUHUISHOU_ORDER_CANCEL, 
                "POST", 
                params, 
                Object.class
            );

            log.info("速回收订单取消响应: {}", Jsons.toJsonString(response));

            if (response != null && response.getCode() == 200) {
                log.info("速回收订单取消成功，订单号: {}", orderNo);
            } else {
                log.error("速回收订单取消失败，订单号: {}, 响应: {}", orderNo, response);
            }

            return response;

        } catch (Exception e) {
            log.error("取消速回收订单异常，订单号: {}", orderNo, e);
            throw Ex.business("取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 验证订单同步条件
     * 包括：订单金额、订单类型、城市限制等
     */
    private void validateOrderSyncConditions(OrderEntity orderInfo, OrderAddressEntity orderAddress) {
        log.info("开始验证订单同步条件，订单ID: {}", orderInfo.getOrderId());

        //0.验证订单渠道
        validateOrderChannel(orderInfo);

        // 1. 验证订单
        if (!suhuishouSyncService.canSyncToSuhuishou(
                orderInfo.getOrderType(),
                orderInfo.getOrderPrice(),
                orderAddress.getUserPhone(),
                orderAddress.getCityCode())) {
            log.warn("订单不满足同步条件，订单ID: {}, 订单金额: {}, 用户手机号: {}, 城市编码: {}",
                    orderInfo.getOrderId(),
                    orderInfo.getOrderPrice(),
                    orderAddress.getUserPhone(),
                    orderAddress.getCityCode());
            throw Ex.business("订单不满足同步条件，无法同步到速回收");
        }

        
        log.info("订单同步条件验证通过，订单ID: {}", orderInfo.getOrderId());
    }

    /**
     * 验证订单渠道
     */
    private void validateOrderChannel(OrderEntity orderInfo) {
        if(Objects.equals(orderInfo.getPartnerId(),100004L)){
            log.info("订单渠道验证未通过，订单ID: {}, 渠道ID: {}", orderInfo.getOrderId(), orderInfo.getPartnerId());
            throw Ex.business("渠道{}不能同步到速回收，订单ID: {}",orderInfo.getPartnerId(), orderInfo.getOrderId());
        }
    }
    
    /**
     * 验证同步城市限制
     */
    private void validateSyncCity(OrderAddressEntity orderAddress) {
        final String notOrderSyncJson = configApiService.getStringConfig(BizConfigEnum.NOT_ORDER_SYNC_CITY.getConfigKey());
        List<Long> notOrderSyncCityList = Jsons.parseArray(notOrderSyncJson, Long.class);
        
        if (notOrderSyncCityList != null && notOrderSyncCityList.contains(orderAddress.getCityCode())) {
            log.warn("城市不支持同步，订单ID: {}, 城市: {}, 城市代码: {}", 
                    orderAddress.getOrderId(), orderAddress.getCity(), orderAddress.getCityCode());
            throw Ex.business("当前城市{}不支持同步订单到速回收", orderAddress.getCity());
        }
    }

    /**
     * 获取订单信息
     */
    private OrderEntity getOrderInfo(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if(Objects.isNull(orderEntity)){
            throw Ex.business("订单不存在");
        }
        return orderEntity;
    }

    /**
     * 获取订单产品信息
     */
    private OrderProductEntity getOrderProduct(Long orderId) {
        OrderProductEntity orderProductEntity = orderProductRepository.selectByOrderId(orderId);
        if(Objects.isNull(orderProductEntity)){
            throw Ex.business("订单产品信息不存在");
        }
        return orderProductEntity;
    }

    /**
     * 获取订单地址信息
     */
    private OrderAddressEntity getOrderAddress(Long orderId) {
        OrderAddressEntity orderAddressEntity = orderAddressRepository.selectByOrderId(orderId);
        if(Objects.isNull(orderAddressEntity)){
            throw Ex.business("订单地址信息不存在");
        }
        return orderAddressEntity;
    }

    /**
     * 构建创建订单的请求参数
     */
    private Map<String, Object> buildCreateOrderParams(OrderEntity orderInfo,
                                                       OrderProductEntity orderProduct,
                                                       OrderAddressEntity orderAddress) {
        Map<String, Object> params = new HashMap<>();
        
        // 地区编码
        params.put("adCode", orderAddress.getDistrictCode());
        
        // 预约时间（毫秒时间戳）
        if (orderInfo.getAppointEndTime() != null) {
            params.put("appointEndTime", orderInfo.getAppointEndTime().getTime());
        }
        if (orderInfo.getAppointStartTime() != null) {
            params.put("appointStartTime", orderInfo.getAppointStartTime().getTime());
        }
        
        // 奖励价格
        params.put("bonusPrice", orderInfo.getBonusPrice() != null ? orderInfo.getBonusPrice() : 0);
        
        // 评估ID
        params.put("evaluateId", orderProduct.getEvaluateId());
        
        // 订单类型
        params.put("orderType", orderInfo.getOrderType());
        
        // 合作方订单号
        params.put("partnerOrderNo", orderInfo.getOrderNo());
        
        // 备注
        params.put("remark", "");
        
        // 回调通知URL
        params.put("notifyUrl", "https://api.chushouya.com/open/suhuishouPush/callback");
        
        // 用户地址
        params.put("userAddress", orderAddress.getAddress());
        
        // 用户电话
        params.put("userPhone", orderAddress.getUserPhone());
        
        // 用户姓名
        params.put("userName", orderAddress.getUserName());
        
        return params;
    }

    /**
     * 处理订单创建成功的后续逻辑
     */
    private void handleCreateOrderSuccess(Long orderId, ResponseDTO<SuhuishouOrderSubmitDTO> response) {
        try {
            if (response.getData() != null) {
                SuhuishouOrderSubmitDTO data = response.getData();
                orderLogService.addOrderActionLog(orderId, OrderActionEnum.FOLLOW_ORDER.value(), Jsons.toJsonString(response));
                OrderEntity updateOrder = new OrderEntity();
                updateOrder.setOrderId(orderId);
                updateOrder.setPartnerOrderNo(data.getOrderNo());
                updateOrder.setUpdateTime(Dates.getTimeNow());
                orderRepository.updateByPrimaryKeySelective(updateOrder);

            }
            
        } catch (Exception e) {
            log.error("处理订单创建成功后续逻辑失败，订单ID: {}", orderId, e);
        }
    }

    /**
     * 创建错误响应
     */
    private ResponseDTO<SuhuishouOrderSubmitDTO> createErrorResponse(String message) {
        ResponseDTO<SuhuishouOrderSubmitDTO> response = new ResponseDTO<>();
        response.setCode(400);
        response.setMsg(message);
        response.setData(null);
        return response;
    }
}
